#include "../include/redis_pool.h"
#include "redis_pool.h"
#include "../include/conf_reader.h"
redis_pool * redis_pool::pool=nullptr;


redis_pool::redis_pool()
{
    //先初始化锁
    this->is_close=false;
    this->redis_list_num=0;

    if(pthread_mutex_init(&this->pool_mutex,NULL)!=0){
        perror("锁资源初始化失败");
        return;
    }
    std::string ip=conf_reader::get_conf_reader_instance()->get_value_from_key("redisIp",IP);
    int port=std::atoi(conf_reader::get_conf_reader_instance()->get_value_from_key("redisPort","6380"));
    int pool_sizes=std::atoi(conf_reader::get_conf_reader_instance()->get_value_from_key("redisPoolSize","10"));
    std::string passwd=conf_reader::get_conf_reader_instance()->get_value_from_key("redisPassWord","Root1234!");
    this->redis_pool_sizes=pool_sizes;
    for(int i=0;i<redis_pool_sizes;++i){
        
        
        MyRedis * new_redis=this->create_one_redis(ip.c_str(),port);
        if(new_redis){
            
            new_redis->AUTH(passwd.c_str());
            this->redis_list.push_back(new_redis);
            this->redis_list_num++;
        }
    }


}

MyRedis *redis_pool::create_one_redis(const char *ip, int port)
{
   MyRedis * _redis=new MyRedis();
   if(_redis->connect_redis(ip,port)){  //成功连接上
    return _redis;
   }else{
    
    delete _redis;
    return nullptr;
   }
    
}

MyRedis *redis_pool::get_one_redis()
{
    
    if(this->is_close==true){
        return nullptr; //如果程序需要关闭
    }


    if(this->redis_list_num>0){
        pthread_mutex_lock(&this->pool_mutex);
        auto redis_item=this->redis_list.front();
        
        redis_list.pop_front();
        --redis_list_num;
        pthread_mutex_unlock(&this->pool_mutex);
        return redis_item;
    }
    
    
    return nullptr;
}

bool redis_pool::give_back_one_redis(MyRedis * old_redis)
{
    if(this->is_close==true){
        delete old_redis;

        return false; //如果程序需要关闭
    }

    

    pthread_mutex_lock(&this->pool_mutex);          //这里就没有去考虑加锁失败的情况了
    this->redis_list.push_back(old_redis);
    ++this->redis_list_num;
    pthread_mutex_unlock(&this->pool_mutex);

    return true;
}

redis_pool::~redis_pool()
{
    for(auto it=this->redis_list.begin();it!=redis_list.end();++it){

        delete *it; //释放的动作放在它的析构函数里
        
    }
    
    printf("redis_pool析构完成");
}